<template>
    <div class="flex align-center justify-center chat-bg" :style="'height: '+windowHeight+'px;width:'+windowWidth+'px;'">
        <div class="chat flex justify-between" :style="'height: '+chatHeight+'px;'">
            <!--左-->
            <div style="display: flex;flex-direction:column;width: 320px;background-color: #292B2E;" :style="'height: '+chatHeight+'px;'">

                <!--一-->
                <div class="flex align-center" style="height: 75px;justify-content: space-between;">
                    <div class="flex align-center justify-center">
                        <div style="margin-left: 15px;margin-right: 15px;">
                            <img src="../../../assets/logo.png" style="width: 54px;height: 54px;border-radius: 50%;border: 1px solid #4F5054;">
                        </div>
                        <span style="color: #E8E9E9;font-size: 18px;">{{userName}}</span>
                    </div>
                    <div class="flex align-center justify-center">
                        <span class="icon iconfont icon-tianjia1"
                              style="color: #CCCCCC;margin-right: 15px;font-size: 18px;cursor:pointer;"
                              @click="addMenu"></span>
                        <span class="icon iconfont icon-liebiao"
                              style="color: #CCCCCC;margin-right: 15px;font-size: 18px;cursor:pointer;"
                              @click="moreMenu"></span>
                    </div>
                </div>


                <!--二-->
                <div class="flex justify-center align-center"
                     style="background-color: #33353A;height: 50px;">
                    <div class="flex justify-center align-center" style="background-color: #4F5054;width: 290px;height: 34px;border-radius: 5px;">
                        <div class="flex justify-center align-center" style="flex: 1;">
                            <span class="icon iconfont icon-sousuo" style="color: #CCCCCC;"></span>
                        </div>
                        <!--<div class="flex" style="flex: 11;color: #CCCCCC;">查找联系人或群</div>-->
                        <div class="flex" style="flex: 11;">
                            <input type="text" class="searchbox"
                                   style="width: 262px;caret-color:white;background-color:#4F5054;margin: 0;padding: 0;border: 1px solid #4F5054;outline:none;color: #CCCCCC;" placeholder="查找联系人或群"></input>
                        </div>
                    </div>

                </div>
                <div style="height: 1px;background-color: #4F5054;"></div>

                <!--三-->
                <div style="display: flex;flex-direction:column;height: 780px;overflow-y: auto;" class="scroll-y">
                    <div v-for="(item,index) in friendList" :key="index" style="height: 78px;" >
                        <div :ref="'msgListDetail'+index"
                             class="flex align-center justify-between"
                             style="background-color: #33353A;height: 77px;cursor: pointer;"
                             :style=""
                             @mouseenter="mouseenter(index)"
                             @mouseleave="mouseleave(index)"
                             @click="clickLeft(index)">
                            <div class="flex" style="flex: 1;">
                                <img src="../../../assets/logo.png" style="width: 52px;height: 52px;border-radius: 50%;margin-left: 15px;margin-right: 15px;border: 1px solid #4F5054;">
                            </div>
                            <div class="flex flex-column" style="flex: 4;">
                                <div class="flex align-center justify-between" style="margin-bottom: 10px;">
                                    <span style="color: #E8E9E9;font-size: 14px;">{{item.code}}</span>
                                    <span style="margin-right: 15px;color: #959595;font-size: 12px;">05-19</span>
                                </div>
                                <div class="flex align-center justify-between">
                                    <span style="color: #959595;font-size: 14px;">测试专用数据，哈哈哈</span>
                                    <span class="flex align-center justify-center"
                                          style="margin-right: 15px;background-color: #FF2C34;width: 30px;height: 18px;color: #FFFFFF;border-radius: 15px;">41</span>
                                </div>
                            </div>
                        </div>
                        <div style="background-color: #292B2E;height: 1px;"></div>
                    </div>
                </div>
                <!--</div>-->

                <div style="display: flex;background-color: #33353A;height: 48px;"></div>
            </div>
            <!--右-->
            <div v-if="current==-1" class="flex align-center justify-center">
                <span class="flex align-center justify-center" style="color: #AEB2B8;font-size: large;width: 830px;"
                      :style="'line-height: '+chatHeight+'px;'">您还未选中或发起聊天，快去跟好友聊一聊吧</span>
            </div>
            <div v-else class="flex flex-column align-center justify-center flex-1">
                <div style="height: 60px;"></div>
                <!--聊天记录列表-->
                <div class="flex flex-3">
                    <div ref="chatMsg" class="flex flex-column" style="width: 830px;">
                        <div v-for="(item, index) in chatMsg" :key="index" class="flex flex-column"
                             style="margin-left: 15px;margin-right: 15px;">
                            <div class="flex align-center"
                                 :class="[userId==item.userId?'flex-row-reverse':'flex-row']"
                                 style="margin-top: 15px;margin-bottom: 15px;">
                                <el-image :src="item.avatar" style="width: 52px;height: 52px;border-radius: 3px;"></el-image>

                                <div class="flex"
                                     :style="userId==item.userId?'padding-right: 30px;':'padding-left: 30px;'">
                                    <div class="frame flex">
                                        <span :class="[userId==item.userId?'triangle-right':'triangle-left']"></span>
                                        <span class="flex align-center justify-center" style="font-size: 20px;padding-left: 15px;padding-right: 15px;"
                                        :style="">{{item.context}}</span>
                                    </div>
                                </div>

                            </div>
                        </div>
                    </div>
                </div>
                <!--<div style="background-color: #dddddd;width: 830px;height: 2px;"></div>-->
                <!--发送栏位-->
                <div class="flex flex-1 flex-column align-center justify-center"
                     style="width: 830px;background-color: #ffffff; padding-left: 15px;padding-right: 15px;">
                    <div class="flex" style="width: 800px;height: 35px;">
                        <span class="icon iconfont icon-biaoqing" style="font-size: 25px;margin-right: 15px;cursor: pointer;"></span>
                        <span class="icon iconfont icon-tupian" style="font-size: 25px;margin-right: 15px;cursor: pointer;"></span>
                        <span class="icon iconfont icon-lianjie1" style="font-size: 25px;margin-right: 15px;cursor: pointer;"></span>
                        <span class="icon iconfont icon-tongzhi" style="font-size: 25px;margin-right: 15px;cursor: pointer;"></span>
                    </div>
                    <div class="flex flex-1 flex-column justify-center" style="width: 800px;border: 1px solid #ffffff;">
                        <textarea class="flex flex-3"
                                  style="width: 800px;background-color: #ffffff;border-color: #ffffff;
                                    resize: none;font-size: 20px;outline:none;"
                                  v-model="sendContext"></textarea>
                        <div class="flex align-center justify-between">
                            <div class="flex"></div>
                            <!--<div class="flex">按下Enter发送内容/ Ctrl+Enter换行</div>-->
                            <!--<div class="flex">Enter换行 / 按下Ctrl+Enter发送内容</div>-->
                            <div class="flex align-center justify-center"
                                 style="cursor: pointer;width: 75px;height: 26px;background-color: #eeeeee;font-size: 15px;"
                                 @click="sendWebsocketMsg">发送</div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <!--<div style="position: fixed;z-index: 999;background-color: #EBEAEA;-->
        <!--width: 240px;height: 240px;right: 20px;top: 10px;"-->
             <!--class="flex flex-column align-center justify-center">-->
            <!--<div style="width:100%;" class="flex">-->
                <!--<el-image :src="require('../../../assets/img/001.jpg')"-->
                          <!--style="width:auto;height: 120px;position: absolute;top: 0px;"-->
                          <!--fit="cover"></el-image>-->
                <!--<div style="position: relative;top: 0px;margin-left: 20px;margin-right: 20px;" class="flex">-->
                    <!--<el-image :src="require('../../../assets/img/005.jpg')" style="width:65px;height: 65px;border-radius: 50%;" fit="cover"></el-image>-->

                <!--</div>-->
            <!--</div>-->


        <!--</div>-->

        <!--弹窗区-->

        <!--菜单-->
        <div v-if="activeAddMenu" class="flex flex-column"
             style="position: absolute;z-index: 999;width: 130px;background-color: white;"
            :style="addMenuSystle">
            <span class="flex align-center"
                  style="height: 50px;cursor:pointer;font-size: 15px;margin-left: 20px;"
                  @click="addFriend">
                添加好友
            </span>
            <span class="flex align-center" style="height: 50px;cursor:pointer;font-size: 15px;margin-left: 20px;">
                新建群聊
            </span>
        </div>

        <div v-if="activeMoreMenu" class="flex flex-column"
             style="position: absolute;z-index: 999;width: 130px;background-color: white;"
             :style="moreMenuSystle">
            <span class="flex align-center"
                  style="height: 50px;cursor:pointer;font-size: 15px;margin-left: 20px;"
                  @click="[showFriendList(),activeFriendList = true]">
                好友列表
            </span>
            <span class="flex align-center" style="height: 50px;cursor:pointer;font-size: 15px;margin-left: 20px;">
                选择群聊
            </span>
        </div>
        <!--菜单具体内容-->
        <el-dialog title="添加好友" :visible.sync="activeAddFriend">
            <div class="flex align-center justify-center">
                <input placeholder="请输入好友ID" v-model="friendId" style="width: 300px;height: 40px;"></input>
                <!--<span style="cursor: pointer;" @click="add"></span>-->

            </div>
            <div class="flex align-center justify-center" :style="addFriendResultMsg=='添加成功！'?'color:green;':'color:red;'">{{addFriendResultMsg}}</div>
            <span slot="footer" class="dialog-footer">
                  <el-button @click="activeAddFriend = false">取 消</el-button>
                  <el-button type="primary" @click="add">添 加</el-button>
            </span>
        </el-dialog>
        <el-dialog title="好友列表" :visible.sync="activeFriendList">
            <div v-if="friendList.length>0">
                <div class="flex flex-1">
                    <div class="flex flex-1">索引</div>
                    <div class="flex flex-1">好友ID</div>
                    <div class="flex flex-1">好友名字</div>
                </div>
                <div v-for="(item, index) in friendList" :key="index" class="flex flex-column">
                    <div class="flex flex-1">
                        <div class="flex flex-1">{{index+1}}</div>
                        <div class="flex flex-1">{{item.id}}</div>
                        <div class="flex flex-1">{{item.code}}</div>
                    </div>
                </div>
            </div>

            <span slot="footer" class="dialog-footer">
                  <el-button @click="[activeFriendList = false, activeMoreMenu = false]">取 消</el-button>
                  <el-button type="primary" @click="[activeFriendList = false, activeMoreMenu = false]">确 定</el-button>
            </span>
        </el-dialog>
    </div>

</template>

<script>
    const wsuri = "ws://127.0.0.1:9021/sevenchat/websocket/wsq";

    export default {
        name: "msg",
        data() {
            return {
                current:-1,
                // tmpCurrent:-1,
                MsgListDetailBackgroundColor:'#292B2E',
                msgListDetailMouseClick:false,
                windowHeight:0,
                windowWidth:0,
                chatHeight:0,
                msgListClass:'',
                token:'',
                userId:-1,
                userName:'',
                nickName:"",
                userLevel:-1,
                friendId:null,
                activeAddMenu:false,
                addMenuSystle:'',
                activeMoreMenu:false,
                moreMenuSystle:'',
                activeAddFriend:false,
                addFriendResultMsg:'',
                activeFriendList:false,
                friendList:[],
                // websock: null,
                // socket:null,
                // client:null,
                //start websocket原生心跳
                lockReconnect : false,//避免重复连接
                wsUrl: "ws://127.0.0.1:9021/sevenchat/websocket/wsq",
                ws : null,
                tt : null,
                heartCheck :null,//心跳检测
                //end
                currentChatUserId:null,//当前对话的群或用户的id
                sendContext:null,
                chatMsg:[],
                // chatMsg:[{
                //     userId:1,
                //     context:"小张，小王，开会了，3楼会议室",
                //     avatar:require('../../../assets/img/001.jpg')
                // },{
                //     userId:2,
                //     context:"哦哦，好的",
                //     avatar:require('../../../assets/img/002.jpg')
                // },{
                //     userId:3,
                //     context:"收到",
                //     avatar:require('../../../assets/img/003.jpg')
                // },{
                //     userId:1,
                //     context:"@所有人，带好笔和纸",
                //     avatar:require('../../../assets/img/001.jpg')
                // }],
                sendMsg:{toUserId:{
                        fromUserId:"29603764498333696",
                        context:""
                    }}
            }
        },
        mounted:function(){
            this.token = localStorage.getItem('accessToken');
            console.log(this.token);
            if(this.token==null){
                this.$router.push({name:'login'});
            }


            this.windowHeight = document.documentElement.clientHeight;
            this.windowWidth = document.documentElement.clientWidth;
            this.chatHeight = this.windowHeight - 20;
            // this.windowHeight = window.innerHeight;
            console.log(this.windowHeight);
            // :style="'height:'+windowHeight+';'"
            //   style="background-color: red;height: 800px;"


            this.userId = localStorage.getItem('userId');
            this.userName = localStorage.getItem('userName');
            this.nickName = localStorage.getItem('nickName');
            this.userLevel = localStorage.getItem('userLevel');
            this.showFriendList();
        },
        created() {
            // this.initWebSocket();
            this.createWebSocket(this.wsUrl);
        },
        destroyed() {
            // if(this.client != null){
            //     this.client.disconnect(function(){
            //
            //     });
            // }
            // this.socket = null;
            // this.client = null;
        },
        methods:{
            mouseenter(index){
                this.$refs['msgListDetail'+index][0].style.backgroundColor = '#3A3C42';

                // console.log(this.$refs['msgListDetail'+index][0].style.backgroundColor);
                // console.log(this.$refs['msgListDetail'][0].style.backgroundColor);
                // this.current = index;
                // this.listMouseEventBgColor = 'background-color: #3A3C42;';
            },
            mouseleave(index){
                if(this.current == index){
                    this.$refs['msgListDetail'+index][0].style.backgroundColor = this.MsgListDetailBackgroundColor;
                    return
                }
                this.$refs['msgListDetail'+index][0].style.backgroundColor = '#33353A';
            },
            clickLeft(index){
                // 让原元素样式恢复如初
                if(this.current > 0){
                    this.$refs['msgListDetail'+this.current][0].style.backgroundColor = '#33353A';
                }
                //记录新索引
                this.current = index;
                this.$refs['msgListDetail'+index][0].style.backgroundColor = '#292B2E';
                //更新当前沟通的用户或群的id
                this.currentChatUserId = this.friendList[index].id;
                // this.initWebSocket();
                // this.websocketonmessage();
            },
            addMenu(e){
                this.activeMoreMenu = false;
                console.log(e);
                // e.pageX;
                this.addMenuSystle = `left:${e.pageX-117}px;top:${e.pageY+30}px;`;
                this.activeAddMenu = !this.activeAddMenu;
            },
            moreMenu(ex){
                this.activeAddMenu = false;
                this.moreMenuSystle = `left:${ex.pageX-120}px;top:${ex.pageY+30}px;`;
                this.activeMoreMenu = !this.activeMoreMenu;
            },
            addFriend(e){
                this.activeAddMenu = false;
                this.activeMoreMenu = false;
                this.activeAddFriend = !this.activeAddFriend;
            },
            add(){
                this.$axios.post('/sevenchat/api/user/v1/friend/add',{'userId':this.userId, 'friendId':this.friendId,'userType':1}, {
                    headers: {
                        // authorization: 'Bearer '+this.token
                        token:this.token
                    }
                })
                    .then((res)=>{

                        console.log(res.data);

                        if(res.data.code=='10000'){
                            this.addFriendResultMsg = '添加成功！';
                            // this.activeAddFriend = false;
                        }else{
                            this.addFriendResultMsg = res.data.message;
                        }
                    })
                    .catch((err)=>{
                        console.error(err);
                    });
            },
            showFriendList(){
                this.$axios.post('/sevenchat/api/user/v1/friend/list',{'id':this.userId, 'code':this.userName}, {
                    headers: {
                        // authorization: 'Bearer '+this.token
                        token:this.token
                    }
                })
                .then((res)=>{

                    console.log(res.data);
                    if(res.data.code=='10000'){
                        this.friendList = res.data.data;
                    }

                    // if(res.data.code=='10000'){
                    //     this.addFriendResultMsg = '添加成功！';
                    //     this.activeAddFriend = false;
                    // }else{
                    //     this.addFriendResultMsg = res.data.message;
                    // }
                })
                .catch((err)=>{
                    console.error(err);
                });

            },
            initWebSocket(){ //初始化weosocket
                const wsuri = "ws://127.0.0.1:9021/sevenchat/websocket/wsq";
                //1) socket连接对象也可通过WebSocket(不通过SockJS)连接
                this.socket =new WebSocket(wsuri);
                this.client = Stomp.over(this.socket);
                //2) stompClient.connect()方法签名：
                // client.connect(headers, connectCallback, errorCallback);
                this.client.connect({}, function connectCallback(){
                    console.log('连接成功');
                }, function connectCallback(){

                });
                // this.client.subscribe(destination url, callback[, headers])
                // this.client.subscribe(wsuri, function callback(message){
                //     console.log(message)
                // });
                //其中headers表示客户端的认证信息，如：
                // let headers = {
                //     login: 'mylogin',
                //     passcode: 'mypasscode',
                //     // additional header
                //     'client-id': 'my-client-id'
                // };
                // 若无需认证，直接使用空对象 “{}” 即可；
                // connectCallback 表示连接成功时（服务器响应 CONNECTED 帧）的回调方法；
                // errorCallback 表示连接失败时（服务器响应 ERROR 帧）的回调方法，非必须；
                //断开连接   若要从客户端主动断开连接，可调用 disconnect() 方法
                //该方法为异步进行，因此包含了回调参数，操作完成时自动回调；
                // client.disconnect(function(){
                //     alert("See you next time!");
                // });
                //心跳机制
                //若使用STOMP 1.1 版本，默认开启了心跳检测机制，可通过client对象的heartbeat field进行配置（默认值都是10000 ms）：
                this.client.heartbeat.outgoing = 1000;  // client will send heartbeats every 20000ms
                this.client.heartbeat.incoming = 0;      // client does not want to receive heartbeats from the server
            },
            websocketonopen(){ //连接建立之后执行send方法发送数据
                let actions = {"test":"12345"};
                // this.websocketsend(JSON.stringify(actions));
            },
            sendWebsocketMsg(){
                let toId = String(this.currentChatUserId);
                // console.log(toId);
                let sendData = {};
                sendData[toId] = {
                    "from":this.userId,
                    "context":this.sendContext
                };
                this.ws.send(JSON.stringify(sendData));
                // this.client.send('/', {}, JSON.stringify(sendData));
                //     userId:1,
                //     context:"小张，小王，开会了，3楼会议室",
                //     avatar:require('../../../assets/img/001.jpg')
                this.chatMsg.push({
                    userId:this.userId,
                    context:this.sendContext,
                    avatar:require('../../../assets/img/001.jpg')
                });
                this.sendContext = null;
            },
            //start websocket
            heartCheckStart(timeout,timeoutObj,serverTimeoutObj){
                // timeout: 3000,
                //     timeoutObj: null,
                //     serverTimeoutObj: null,
                console.log('start');

                timeoutObj && clearTimeout(timeoutObj);
                serverTimeoutObj && clearTimeout(serverTimeoutObj);
                timeoutObj = setTimeout(function(){
                    //这里发送一个心跳，后端收到后，返回一个心跳消息，
                    console.log('55555');
                    this.ws.send("123456789");
                    serverTimeoutObj = setTimeout(function() {
                        console.log(111);
                        console.log(ws);
                        this.ws.close();
                        // createWebSocket();
                    }, timeout);

                }, timeout)
            },
            createWebSocket() {
                try {
                    this.ws = new WebSocket(this.wsUrl);
                    this.init();
                } catch(e) {
                    console.log('catch');
                    this.reconnect(this.wsUrl);
                }
            },
            init() {
                this.ws.onclose = function () {
                    console.log('链接关闭');
                    this.reconnect(this.wsUrl);
                };
                this.ws.onerror = function() {
                    console.log('发生异常了');
                    this.reconnect(this.wsUrl);
                };
                this.ws.onopen = function () {
                    //心跳检测重置
                    this.heartCheckStart(3000,null,null);
                };
                this.ws.onmessage = function (event) {
                    //拿到任何消息都说明当前连接是正常的
                    console.log('接收到消息');
                    this.heartCheckStart(3000,null,null);
                }
            },
            reconnect(url) {
                if(this.lockReconnect) {
                    return;
                };
                this.lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                this.tt && clearTimeout(this.tt);
                this.tt = setTimeout(function () {
                    this.createWebSocket(url);
                    this.lockReconnect = false;
                }, 4000);
            }

            //end websocket
        }

    }
</script>

<style scoped>
    .chat-bg{
        background-color:#D2D4E0;
        /*display: flex;*/
    }
    .chat{
        /*margin: auto;*/
        /*height: 890px;*/
        width: 1150px;
        /*align-self: center;*/
        background-color: #EEEEEE;
    }
    /*一行文本垂直居中，使用line-height*/
    .align-center-text{
        /*line-height: 200px;*/
        /*text-align: center;*/
        overflow: hidden;
    }
    /*滚动条尺寸*/
    .scroll-y::-webkit-scrollbar{
        width: 5px;
        height: 780px;
    }
    /*滚动条里面小方块*/
    .scroll-y::-webkit-scrollbar-thumb{
        border-radius: 10px;
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        background: #ADAAA9;
    }
    /*滚动条里面轨道*/
    .scroll-y::-webkit-scrollbar-track{
        -webkit-box-shadow: inset 0 0 5px rgba(0,0,0,0.2);
        border-radius: 10px;
        background: #E0DEDE;
    }
    .searchbox::-webkit-input-placeholder{
        color: #CCCCCC;
        font-size:13px;
    }
    .msg-textarea{

    }
    .frame{
        /*width: 200px;*/
        height: 52px;
        /*border:1px solid #000;*/
        background-color: #FFFFFF;
        border-radius: 10px;
        position: relative;
    }
    .triangle-left{
        width: 12px;
        height: 12px;
        display: inline-block;
        position: absolute;
        top: 13px;
        left: -7px;
        /*bottom: -12px;*/
        /*right: 30px;*/
        background-color: #FFFFFF;
        /*border-top: 1px solid #000;*/
        /*border-right: 1px solid #000;*/
        transform:rotate(225deg);
        -ms-transform:rotate(225deg);     /* IE 9 */
        -moz-transform:rotate(225deg);    /* Firefox */
        -webkit-transform:rotate(225deg); /* Safari 和 Chrome */
        -o-transform:rotate(225deg);  /* Opera */
    }
    .triangle-right{
        width: 12px;
        height: 12px;
        display: inline-block;
        position: absolute;
        top: 13px;
        right: -5px;
        /*bottom: -12px;*/
        /*right: 30px;*/
        background-color: #FFFFFF;
        /*border-top: 1px solid #000;*/
        /*border-right: 1px solid #000;*/
        transform:rotate(225deg);
        -ms-transform:rotate(225deg);     /* IE 9 */
        -moz-transform:rotate(225deg);    /* Firefox */
        -webkit-transform:rotate(225deg); /* Safari 和 Chrome */
        -o-transform:rotate(225deg);  /* Opera */
    }
</style>
